package sg.edu.nus.iss.phoenix.schedule.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sg.edu.nus.iss.phoenix.authenticate.delegate.UserDelegate;
import sg.edu.nus.iss.phoenix.authenticate.entity.User;
import sg.edu.nus.iss.phoenix.core.controller.FCUtilities;
import sg.edu.nus.iss.phoenix.radioprogram.delegate.RPDelegate;
import sg.edu.nus.iss.phoenix.radioprogram.entity.RPSearchObject;
import sg.edu.nus.iss.phoenix.radioprogram.entity.RadioProgram;
import sg.edu.nus.iss.phoenix.schedule.delegate.ScheduleDelegate;
import sg.edu.nus.iss.phoenix.schedule.entity.Schedule;
import sg.edu.nus.iss.phoenix.utils.DateHolder;
import sg.edu.nus.iss.phoenix.utils.PhoenixUtils;

/**
 * Servlet implementation class ProcessController
 * 
 * @author Low  Kheng Hian (A0092668N)
 * @author Nang Sai Hom (A0092617B)
 *  
 * @version 1.0 2012/9/27
 */


@WebServlet("/ScheduleController/*")
public class ScheduleController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ScheduleController() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String selection = FCUtilities.stripPath(request.getPathInfo())
				.toLowerCase();
		ScheduleDelegate scheduleDelegate = new ScheduleDelegate();
		RPDelegate rpDelegate = new RPDelegate();
		switch (selection) {
		case "create":
			RequestDispatcher rd2 = request
					.getRequestDispatcher("/pages/schedule/setupschedule.jsp");
			List<RadioProgram> programs = rpDelegate.findAllRP();
			request.setAttribute("programs", programs);
			// System.out.println("programs " + programs);
			request.setAttribute("insert", "true");
			rd2.forward(request, response);
			break;
		case "copy":
			String sid = request.getParameter("schedule_id");
			if (!PhoenixUtils.isNumeric(sid)) {
				// System.out.println("Invalid input");
			}
			Schedule oldSchedule = new Schedule();
			oldSchedule.setScheduleId(Integer.parseInt(sid));
			oldSchedule = scheduleDelegate.loadSchedule(oldSchedule);
			
			Schedule newSchedule = scheduleDelegate.copySchedule(oldSchedule);
			request.setAttribute("schedule", newSchedule);
			request.setAttribute("insert", "false");
			
			rd2 = request.getRequestDispatcher("/pages/schedule/setupschedule.jsp");
			rd2.forward(request, response);
			break;
		case "delete":
			String id = request.getParameter("schedule_id");
			if (!PhoenixUtils.isNumeric(id)) {
				// System.out.println("Invalid input");
			}
			Schedule sch = new Schedule();
			sch.setScheduleId(Integer.parseInt(id));
			scheduleDelegate.deleteSchedule(sch);

			rd2 = request.getRequestDispatcher("/controller/loadschedule");
			rd2.forward(request, response);
			break;
		case "process":
			Schedule editschedule = new Schedule();

			User presenter = new User();
			UserDelegate udelegate = new UserDelegate();
			presenter.setId(request.getParameter("presenterId"));
			presenter = udelegate.loadUser(presenter);
			editschedule.setPresenter(presenter);

			User producer = new User();
			producer.setId(request.getParameter("producerId"));
			producer = udelegate.loadUser(producer);
			editschedule.setProducer(producer);

			RadioProgram program = new RadioProgram();
			program.setProgram_id(Integer.parseInt(request
					.getParameter("program_id")));
			editschedule.setProgram(program);
			
			String start = request.getParameter("start_time");
			String end = request.getParameter("end_time");
			// System.out.println(" in controoller " + start);
			// System.out.println(" in controoller " + end);
			 editschedule.setStartTime(start);
			 editschedule.setEndTime(end);
			 
			String ins = (String) request.getParameter("ins");
			if (ins.equalsIgnoreCase("true")) {
				scheduleDelegate.insertSchedule(editschedule);
			} else if (ins.equalsIgnoreCase("false")) {
				String schedule_id = request.getParameter("schedule_id");
				if (!PhoenixUtils.isNumeric(schedule_id)) {
					// System.out.println("Invalid input");
				}
				editschedule.setScheduleId(Integer.parseInt(schedule_id));
				// System.out.println("Updating schedule " + editschedule);
				scheduleDelegate.updateSchedule(editschedule);
			}
			rd2 = request.getRequestDispatcher("/controller/loadschedule");
			rd2.forward(request, response);
			break;
		case "edit":
			Schedule schedule = new Schedule();
			String scheduleId = request.getParameter("schedule_id");
			if (!PhoenixUtils.isNumeric(scheduleId)) {
				// System.out.println("Invalid input");
			}

			schedule.setScheduleId(Integer.parseInt(scheduleId));
			Schedule loadedSchedule = scheduleDelegate.loadSchedule(schedule);
			request.setAttribute("schedule", loadedSchedule);

			request.setAttribute("insert", "false");
			// System.out.println("*********** " + loadedSchedule);

			rd2 = request
					.getRequestDispatcher("/pages/schedule/setupschedule.jsp");
			rd2.forward(request, response);
			break;
		case "load":
			ArrayList<Schedule> data2 = scheduleDelegate.findAllSchedule();
			// System.out.println("ssds " + data2);
			request.setAttribute("schedules", data2);
			rd2 = request
					.getRequestDispatcher("/pages/schedule/crudschedule.jsp");
			rd2.forward(request, response);
			break;
		case "search":
			RPDelegate rdel3 = new RPDelegate();
			RPSearchObject search3 = new RPSearchObject();
			ArrayList<RadioProgram> list = new ArrayList<RadioProgram>();
			if (request.getParameter("name") != null
					|| request.getParameter("description") != null) {
				search3.setName(request.getParameter("name"));
				search3.setDescription(request.getParameter("description"));
				list = rdel3.searchPrograms(search3);
			} else {
				list = rdel3.findAllRP();
			}
			request.getSession().setAttribute("searchrplist", list);
			RequestDispatcher rd3 = getServletContext().getRequestDispatcher(
					"/pages/searchrp.jsp");
			;
			rd3.forward(request, response);
			break;
		case "select":
			String date = request.getParameter("date");
			if (date == null) {
				date = new SimpleDateFormat("MM/dd/yy").format(Calendar
						.getInstance().getTime());
			}
			Date date1 = PhoenixUtils.stringToDate(date);

			TreeMap<Integer, DateHolder> availableSlots = new TreeMap<Integer, DateHolder>();
			if (date1 != null) {

				availableSlots = scheduleDelegate.findAvailableSlots(date1);
			}
			// System.out.println(availableSlots);
			request.setAttribute("slots", availableSlots);
			RequestDispatcher rd5 = getServletContext().getRequestDispatcher(
					"/pages/schedule/selectschedule.jsp");

			rd5.forward(request, response);

			break;
		default:
			RPDelegate rpdel4 = new RPDelegate();
			ArrayList<RadioProgram> data4 = rpdel4.findAllRP();
			request.setAttribute("rps", data4);
			RequestDispatcher rd4 = request
					.getRequestDispatcher("/pages/crudrp.jsp");
			rd4.forward(request, response);
			break;
		}
	}

}
